﻿using MediatR;
using Microsoft.IdentityModel.Tokens;
using PublicCommon;
using T_Material.Domain;
using T_Material.Infrastructure.ImpI;
using T_Material.Infrastructure.Interface;
using T_Material.Read.API.Application.Commands.PurchaseCommand;
using T_Material.Read.API.Application.Commands.RequisitionCommand;

namespace T_Material.Read.API.Application.CommandHandlers.RequisitionHandler
{
    public class RequisitionListCommandHandler : IRequestHandler<RequisitionListCommand, PageResult<Requisition>>
    {
        private readonly IRequisitionRepository requisitionRepository;
        public RequisitionListCommandHandler(IRequisitionRepository requisitionRepository)
        {
            this.requisitionRepository = requisitionRepository;
        }
        public async Task<PageResult<Requisition>> Handle(RequisitionListCommand request, CancellationToken cancellationToken)
        {
            var list = requisitionRepository.GetList().Result.Where(x => !x.IsDel).AsQueryable();
            if (!string.IsNullOrEmpty(request.Recipient))
            {
                list = list.Where(x => x.Recipient.Contains(request.Recipient));
            }
            if (!string.IsNullOrEmpty(request.ApprovedBy))
            {
                list = list.Where(x => x.ApprovedBy.Contains(request.ApprovedBy));
            }
            if (request.AuditState == 0)
            {
                list = list.Where(x => x.AuditState == request.AuditState);
            }
            else if(request.AuditState == 1)
            {
                list = list.Where(x => x.AuditState == request.AuditState);
            }
            else if (request.AuditState == 2)
            {
                list = list.Where(x => x.AuditState == request.AuditState);
            }
            else if (request.AuditState == 3)
            {
                list = list.Where(x => x.AuditState == request.AuditState);
            }
            if (!string.IsNullOrEmpty(Convert.ToString(request.RequisitionDate)))
            {
                list = list.Where(x => x.RequisitionDate == request.RequisitionDate);
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            var pagelist = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new PageResult<Requisition>
            {
                List = pagelist,
                PageCount = pageCount,
                TotalCount = totalCount
            };
        }
    }
}
